#!/usr/bin/python
# coding=utf-8
import psycopg2
import time
import sys
import os

#处理UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


#连接数据库
def conn_db(file_id):
    conn = psycopg2.connect("host=opsdb.yazuoyw.com dbname=ops port=5432 user=opser password=opsEr3469")
    print "success"
    print '%s' %file_id
    global cur
    cur = conn.cursor()
    return conn



#获取文件名
def get_filename(file_id):
    conn = conn_db(file_id)
    sql = "select script from sql_contents where sql_order_id=%s;" 
    cur.execute(sql, (file_id,))
    rows = cur.fetchall()
    for row in rows:
    	return row[0]
    conn.commit()

#读取文件内容
def readfile(file_id):
    file_name = get_filename(file_id)
    print '-----------------' ,file_name
    #把文件格式转换为unix
    os.system("dos2unix public/uploads/%s" %file_name)
    res =[]
    f = open("public/uploads/%s" %file_name,"r")
    content = f.read()
    f.close()
    return content 

    #读取完之后删除文件
    #os.system("rm -f ../public/uploads/%s" %file_name)


#将文件内容写入数据库
def write_db(file_id):
	file_row = readfile(file_id)
	#print file_row
	conn = conn_db(file_id)
	add_script = "update sql_contents set script = %s where sql_order_id = %s;"
	change_status = "update sql_orders set status='submitted' where id = %s;"
	cur.execute(add_script, (file_row,file_id))
	cur.execute(change_status,(file_id,))
	conn.commit()
	conn.close()


if __name__ == "__main__":
    try:
        write_db(sys.argv[1])
    except Exception,e:
        print e
    




